package com.kay.springbootRESTful;

import com.kay.springbootRESTful.entity.Account;
import com.kay.springbootRESTful.repository.AccountRepository;
import com.kay.springbootRESTful.repository.AccountRepository;
import com.kay.springbootRESTful.service.CustomerService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class SpringBootResTfulApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootResTfulApplication.class, args);
    }

}

@Configuration
class initDataSource {

    @Bean
    public CommandLineRunner commandLineRunner(AccountRepository accountRepository, CustomerService customerService, ResourceLoader resourceLoader) {
        return args -> {
            Resource resource = resourceLoader.getResource("classpath:MOCK_DATA.csv");
            List<Account> accounts = parseCSVFile(resource, customerService);
            accountRepository.saveAll(accounts);
        };
    }

    private List<Account> parseCSVFile(final Resource resource, CustomerService customerService) throws Exception {
        final List<Account> accounts = new ArrayList<>();
        try {
            try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
                bufferedReader.lines().forEach(line -> {
                    final String[] data = line.split(",");
                    final Account account = new Account();
                    account.setAccountName(data[1]);
                    account.setBalance(new BigDecimal(data[2]));
                    account.setOpeningDate(LocalDate.parse(data[3]));
                    account.setCustomer(customerService.findById(Integer.valueOf(data[0])));
                    accounts.add(account);
                });
                return accounts;
            }
        } catch (IOException e) {
			throw new Exception("转换 CSV file 失败{}", e);
        }
    }
}
